from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKU, GoodsCategory, SPUSpecification
from apps.meiduo_admin.serializers.sku import SKUGoodsSerializer, SKUGoodsCategorySerializer, \
    SPUSpecificationSerializer
from apps.meiduo_admin.utils import UserPageNum


class SKUGoodsView(ModelViewSet):
    '''
        SKU表的增删改查
    '''
    # 指定查询集
    queryset = SKU.objects.all()
    # 指定序列化器
    serializer_class = SKUGoodsSerializer
    # 指定分页器
    pagination_class = UserPageNum
    # 指定权限
    permission_classes = [IsAdminUser]

    # 重写get_queryset方法，根据前端是否传递keyword值返回不同查询结果
    def get_queryset(self):
        # 获取前端传递的keyword值
        keyword = self.request.query_params.get('keyword')
        # 如果keyword是空字符，则说明要获取所有用户数据
        if keyword is None or keyword == '':
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)

    # 获取三级分类信息
    @action(methods=['get'], detail=False)
    def categories(self, request):
        # 查询三级分类数据
        data = GoodsCategory.objects.filter(subs=None)
        s = SKUGoodsCategorySerializer(data, many=True)
        return Response(s.data)

    # 获取规格信息
    def specs(self, request, pk):
        # 1. 查询规格信息
        data = SPUSpecification.objects.filter(spu_id=pk)
        # 2. 序列化返回当前商品的规格信息
        s = SPUSpecificationSerializer(data, many=True)
        return Response(s.data)
